﻿using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace TransformerSystem.UI.Behaviors
{
    public class WindowBehavior : Behavior<Window>
    {
        private IWindowAware Aware
        {
            get
            { 
                return AssociatedObject.DataContext as IWindowAware;
            }
        }
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.Initialized += AssociatedObject_Initialized;
            AssociatedObject.Closing += AssociatedObject_Closing;
            AssociatedObject.Closed += AssociatedObject_Closed;
        }

        private void AssociatedObject_Closing(object sender, System.ComponentModel.CancelEventArgs e)=> e.Cancel = !Aware.CanClosing();

        private void AssociatedObject_Closed(object sender, EventArgs e)=> Aware?.Closed();

        private void AssociatedObject_Initialized(object sender, EventArgs e) => Aware?.Initialized();

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.Initialized -= AssociatedObject_Initialized;
            AssociatedObject.Closing -= AssociatedObject_Closing;
            AssociatedObject.Closed -= AssociatedObject_Closed;
        }
    }
}
